package com.hbsoft.util;

import com.google.gson.Gson;
import com.hb.bean.CallResult;
import com.hb.util.HttpUtil;
import com.hb.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class SendSMS {
	@Value("${hb.sendSMSUrl:}")
	String sendSMSUrl;
	@Value("${hb.api_app_secret:a17aba5bbacfa2a4c2f6d44f03c9c0fa}")
	String api_app_secret;
	@Value("${hb.tokenType:zz}")
	String type;

	@Autowired
	private Gson gson;

	@SuppressWarnings("unchecked")
	public CallResult<String> sendSMSCode(String mobile) throws Exception {
		CallResult<String> result = new CallResult<>();
		Date date = new Date();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String code = getCode(6);
		String content = code + ",1";
		String templateId = "92523";
		String timestamp = format.format(date);
		Map<String, String> map = new HashMap<>();
		map.put("content", content);
		map.put("mobile", mobile);
		map.put("templateId", templateId);
		map.put("timestamp", timestamp);
		String sign = ApiSign.signTopRequest(map, null, this.api_app_secret, "md5");
		Map<String, Object> params = new HashMap<>();
		params.put("timestamp", timestamp);
		params.put("sign", sign);
		params.put("mobile", mobile);
		params.put("content", content);
		params.put("templateId", templateId);
		String sendPost = HttpUtil.sendPost(sendSMSUrl, params);
		try {
			result = this.gson.fromJson(sendPost, result.getClass());
			if (result.getCode().intValue() == 0) {
				result.setData(code);
			}
		} catch (Exception e) {
			result.setCode(400);
			result.setMessage("发送失败");
		}
		result.setCode(0);
		result.setData(code);
		return result;
	}

//	public void sendSMSMatter(String mobile) throws Exception {
//		try {
//			SmsSingleSender sender = new SmsSingleSender(1400072827, "bcb6a03b0b857eb1ef64edd1fb464b81");
//			sender.sendWithParam("86", mobile, 148679, null, "", "", "");
//		} catch (Exception e) {
//			e.printStackTrace();
//
//		}
//	}

	private String getCode(Integer num) {
		Integer code = Integer.valueOf(new SecureRandom().nextInt(999999));
		String zerofill = StringUtil.getZerofill(num.intValue(), code.intValue());
		return zerofill;
	}

}
